package com.xzl.org.learning_situation_analysis.service.Impl;

import com.github.pagehelper.PageInfo;
import com.xzl.org.learning_situation_analysis.dao.UserMapper;
import com.xzl.org.learning_situation_analysis.entity.LoginTicket;
import com.xzl.org.learning_situation_analysis.entity.User;
import com.xzl.org.learning_situation_analysis.service.UserService;
import com.xzl.org.learning_situation_analysis.util.GenericUtil;
import com.xzl.org.learning_situation_analysis.util.PageUtil;
import com.xzl.org.learning_situation_analysis.util.RedisKeyUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author 夏智力
 * @FileName UserServiceImpl
 * @date 2022/4/12 17:19
 * @Software: IntelliJ IDEA
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public User selectByUserName(String userName) {
        return userMapper.selectByUserName(userName);
    }

    @Override
    public int insertUser(User user) {
        return userMapper.insertUser(user);
    }

    @Override
    public PageInfo<User> selectCurrentPageUser(int currentPage, int pageSize) {
        List<User> userAll = userMapper.selectAll();
        PageInfo page = new PageUtil<User>().getPage(currentPage, pageSize, userAll);
        return page;
    }


    @Override
    public int updatePassword(int id, String password) {
        int rows = userMapper.updatePassword(id, password);
        clearCache(id);
        return rows;
    }

    //1.优先从缓存中取值
    private User getCache(int userId) {
        String redisKey = RedisKeyUtil.getUserKey(userId);
        return (User) redisTemplate.opsForValue().get(redisKey);
    }

    //2.取不到时初始化缓存数据
    private User initCache(int userId) {
        User user = userMapper.selectById(userId);
        String redisKey = RedisKeyUtil.getUserKey(userId);
        redisTemplate.opsForValue().set(redisKey, user, 3600, TimeUnit.SECONDS);
        return user;
    }

    //3.数据变更时清除缓存数据
    private void clearCache(int userId) {
        String redisKey = RedisKeyUtil.getUserKey(userId);
        redisTemplate.delete(redisKey);
    }

}
